package org.lookahead.parent.common.utils.jpush;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lookahead.parent.common.utils.ApacheHttpTool;
import org.lookahead.parent.common.utils.HttpResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 极光推送工具类
 */
@Slf4j
@AllArgsConstructor
public class JpushUtil {

    private final static String postUrl = "https://api.jpush.cn/v3/push";

    private String appId;
    private String secret;
    private Boolean apns_production;

    public static JpushUtil build(String appId, String secret, Boolean production) {
        return new JpushUtil(appId, secret, production);
    }
    /**
     * 发送极光push消息
     *
     * @param message 消息体
     * @return Integer
     */
    public Integer push(JpushMessage message) {
        int code = 0;
        if (message == null) {
            return code;
        }
        try {
            log.info("Jpush=send:{}", JSON.toJSONString(message));
            String encoding = DatatypeConverter.printBase64Binary(String.join(":", appId, secret).getBytes(StandardCharsets.UTF_8));
            Map<String, String> headers = MapUtil.of(
                    "Authorization", "Basic " + encoding
            );
            HttpResult result = ApacheHttpTool.httpPostWithJson(postUrl, headers, JSON.toJSONString(message));
            log.info("Jpush=result:{}", JSON.toJSONString(result));
            code = result.getCode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 构建push消息体
     *
     * @param regId 发送对象，null为广播发送
     * @param title 消息标题
     * @param alert 消息内容
     * @param body  app业务传参
     * @return JpushMessage
     */
    public JpushMessage message(List<String> regId, boolean isAll, String title, String alert, Map<String, Object> body) {
        JpushMessage msg = new JpushMessage();

        // 推送平台
        msg.setPlatform("all");

        // 推送目标
        if (isAll) {
            msg.setAudience("all");
        } else if (CollectionUtils.isEmpty(regId)) {
            log.warn("Jpush：没有推送目标，退出");
            return null;
        } else {
            msg.setAudience(MapUtil.of("registration_id", regId));
        }

        // 通知
        JpushMessageNotification notification = new JpushMessageNotification();
        notification.setAlert(alert);
//        notification.setAlternate_alert(message);
        // Android通知
        JpushMessageAndroid android = new JpushMessageAndroid();
        android.setAlert(alert);
        android.setTitle(title);
        if (!ObjectUtils.isEmpty(body)) {
            android.setExtras(new HashMap<>(body));
        }
        // IOS通知
        JpushMessageIos ios = new JpushMessageIos();
        ios.setAlert(MapUtil.<String, String>builder()
                .put("title", title)
                .put("body", alert)
                .build());
        if (!ObjectUtils.isEmpty(body)) {
            ios.setExtras(new HashMap<>(body));
        }
        notification.setIos(ios);
        notification.setAndroid(android);
        msg.setNotification(notification);

        // 自定义消息
        if (!ObjectUtils.isEmpty(body)) {
            msg.setMessage(MapUtil.<String, Object>builder()
                    .put("msg_content", title)
                    .put("extras", new HashMap<>(body))
                    .build());
        }

        // 可选参数
        msg.setOptions(MapUtil.of("apns_production", apns_production));
        return msg;
    }

    /**
     * 测试函数
     */
    public static void main(String[] args) throws InterruptedException {
        // 班级动态消息
        Map<String, Object> msgBodyClassMessage = MapUtil.<String, Object>builder()
                .put("url", "txt/202301/47a66fa46a313e4aa68226ed44a5d699.html")
                .put("classId", "123456")
                .put("messageId", "123123")
                .put("type", JpushMessageType.CLASS_CIRCLE.getCode())
                .build();

        // 系统通知
        Map<String, Object> msgBodySystemNotice = MapUtil.<String, Object>builder()
                .put("url", "https://www.baidu.com")
                .put("messageId", "123123")
                .put("type", JpushMessageType.SYSTEM_NOTIFY.getCode())
                .build();

        // 作业通知
        Map<String, Object> msgBodyAssignments = MapUtil.<String, Object>builder()
                .put("type", JpushMessageType.CLASS_EXERCISE.getCode())
                // 作业ID
                .put("homeworkId", "11111")
                // 班级id
                .put("classId", "222222")
                //班级学科（0中文,1英文）
                .put("subjectType", "0")
                //作业名称
                .put("homeworkName", "作业名称")
                // 1.当前作业 2.补做
                .put("state", "1")
                .build();

        JpushUtil jpush = JpushUtil.build("64f13ce6f48cdf516fb11730", "30874bcbf8946791f7e366c6", false);

        JpushMessage msgClassMessage = jpush.message(
                Arrays.asList("1114a89793bc0f4fd7a", "123"),
                false,
                "您收到1条新的班级动态 " + System.currentTimeMillis(),
                "如何给孩子做英语启蒙？用好这些材料，简单有效孩子喜欢！",
                msgBodyClassMessage
        );
        System.out.println(jpush.push(msgClassMessage));
        TimeUnit.SECONDS.sleep(3);
//
//		JpushMessage msgSysNotice = jpush.build(
//			null,
//			true,
//			"系统通知 " + System.currentTimeMillis(),
//			"这是一条系统通知，点击详见内容",
//			msgBodySystemNotice
//		);
//		System.out.println(jpush.push(msgSysNotice));
//		TimeUnit.SECONDS.sleep(3);
//
//		JpushMessage msgAssignmentsMessage = jpush.build(
//			Arrays.asList("1114a89793b378ce5a7"),
//			false,
//			"您有新的作业待完成 " + System.currentTimeMillis(),
//			StringUtil.format("截止时间:{}, 快去完成吧", DateUtil.formatOddDate(new Date())),
//			msgBodyAssignments
//		);
//		System.out.println(jpush.push(msgAssignmentsMessage));
//		TimeUnit.SECONDS.sleep(3);


//		String sss = StringUtil.format("截止时间:{}, 快去完成吧", DateUtil.formatOddDate(new Date()));
//		System.out.println(sss);
    }
}
